from werkzeug.exceptions import HTTPException
import code
from flask.globals import request
from flask import json

#自定义APIException类，继承HTTPException
class APIException(HTTPException):
    code = 500
    msg = 'sorry, we made a mistake (*￣︶￣)!'
    error_code = 999
    
    def __init__(self, msg=None, code=None, 
                       error_code=None, headers=None):
        
        if code:
            self.code = code
        if error_code:
            self.error_code = error_code
        if msg:
            self.msg = msg
        #调用父类HTTPException的__init__
        super(APIException, self).__init__(msg, None)
    
    #重写父类HTTPException的get_body方法    
    def get_body(self, environ=None):
        body = dict(msg=self.msg,
                    error_code=self.error_code,
                    request=request.method + '' +self.get_url_no_param())
        #将body(字典)通过json进行序列化
        text = json.dumps(body)
        return text
    
    #重写父类HTTPException的get_headers方法
    def get_headers(self, environ=None):
        #Get a list of headers
        return [('Content-Type', 'application/json')]
    
    @staticmethod
    def get_url_no_param():
        full_path = str(request.full_path)
        main_path = full_path.split('?')
        return main_path[0]
    
    
    
    
    
    
    